﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Models.DataBase;

namespace DataRepository
{
  public class Repository<Entity> : IRepository<Entity> where Entity : class, new()
  {

    public readonly WorkContext _dbContext;
    public Repository(WorkContext dbContext)
    {
      _dbContext = dbContext;
    }

    /// <summary>
    /// 删除记录
    /// </summary>
    /// <param name="T"></param>
    /// <returns></returns>
    public Entity Delete(Entity T)
    {
      if (T == null) return null;
      var entity = _dbContext.Set<Entity>().Remove(T).Entity;
      _dbContext.SaveChanges();
      return entity;
    }

    public Entity GetDetailById(Expression<Func<Entity, bool>> exp)
    {
      return _dbContext.Set<Entity>().FirstOrDefault(exp);
    }

    /// <summary>
    /// 检索表格全部内容
    /// </summary>
    /// <returns></returns>
    public List<Entity> GetDataList()
    {
      return _dbContext.Set<Entity>().ToList();
    }

    /// <summary>
    /// 条件检索表格    
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public List<Entity> GetDataList(Expression<Func<Entity, bool>> exp)
    {
      return _dbContext.Set<Entity>().Where(exp).ToList();
    }

    /// <summary>
    /// 分页检索
    /// </summary>
    /// <param name="page"></param>
    /// <param name="limit"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    public List<Entity> GetDataPage(int page, int limit, out int count)
    {
      count = _dbContext.Set<Entity>().Count();
      return _dbContext.Set<Entity>().Skip((page - 1) * limit).Take(limit).ToList();
    }

    /// <summary>
    /// 带条件的分页检索
    /// </summary>
    /// <param name="exp"></param>
    /// <param name="page"></param>
    /// <param name="limit"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    public List<Entity> GetDataPage(Expression<Func<Entity, bool>> exp, int page, int limit, out int count)
    {
      count = _dbContext.Set<Entity>().Count();
      return _dbContext.Set<Entity>().Where(exp).Skip((page - 1) * limit).Take(limit).ToList();
    }


    /// <summary>
    /// 新增记录
    /// </summary>
    /// <param name="T"></param>
    /// <returns></returns>
    public Entity Insert(Entity T)
    {
      if (T == null) return null;
      var entity = _dbContext.Set<Entity>().Add(T).Entity;
      _dbContext.SaveChanges();
      return entity;
    }

    /// <summary>
    /// 修改记录
    /// </summary>
    /// <param name="T"></param>
    /// <returns></returns>
    public Entity Update(Entity T)
    {
      if (T == null) return null;
      var entity = _dbContext.Set<Entity>().Update(T).Entity;
      _dbContext.SaveChanges();
      return entity;
    }
  }
}
